//
//  GPHomeController.m
//  GoldPig
//
//  Created by 虎爷 on 2019/10/16.
//  Copyright © 2019 虎爷. All rights reserved.
//

#import "GPHomeController.h"
#import "GPHomeView.h"
#import "FTRainController.h"
#import "GPTaskView.h"
#import "GPTipView.h"
#import "GPMapController.h"
#import "GPWithdrawalController.h"
#import "GPUpgradeView.h"
#import "GPLevelUpView.h"
#import "GPWorkController.h"


@interface GPHomeController ()
@property (nonatomic, strong)GPHomeView *homeView;

@property (nonatomic,strong) NSNumber *bt_time_1933;
@property (nonatomic, weak) NSTimer *diamondsTimer;
@property (nonatomic, weak) NSTimer *givenNumTimer;
@property (strong, nonatomic) NSNumber *goldNum;
@property (strong, nonatomic) NSNumber *diamondsNum;
@property (strong, nonatomic) NSNumber *givenNum;
@property (strong, nonatomic) NSNumber *capacity;
@property (strong, nonatomic) GPUpgradeView *upgradeView;
@property (strong, nonatomic) GPLevelUpView *levelUpView;
@property (strong, nonatomic) NSNumber *remainNum;
@property (strong, nonatomic) NSNumber *remainTime;
@property (strong, nonatomic) NSNumber *level;
@property (strong, nonatomic) NSNumber *levelStatus;
@property (strong, nonatomic) NSNumber *levelBonusesTypeId;
@property (nonatomic, weak) NSTimer *reTimer;
@end
@implementation GPHomeController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self homeView];
    
    [self upgradeView];
    [self queryOfAppRequest];
    [self getPigInfoResquest];
    [self redEnvelopedRainSearchResquest];
    [self taskBonusesSearchResquest];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    [self userAccountRequest];

}

#pragma mark 懒加载
-(GPHomeView *)homeView{
    if (!_homeView) {
        _homeView = [GPHomeView initGPHomeView];
        _homeView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
        [self.view addSubview:_homeView];
        
        WEAKSELF
        _homeView.rainClickBlock = ^{
            if (self.remainNum.intValue > 0) {
                if (self.remainTime.intValue == 0) {
                    FTRainController *rainVC = [[FTRainController alloc] init];
                    [weakSelf.navigationController pushViewController:rainVC animated:NO];
                    rainVC.refreshBlock = ^{
                        [weakSelf redEnvelopedRainSearchResquest];
                    };
                }else{
                    [SVProgressHUD showImage:NULL_IMAGE status:@"钻石雨时间还没到，请耐心等候"];
                }
            }else{
                [SVProgressHUD showImage:NULL_IMAGE status:@"今日钻石雨已结束"];
            }
        };
  
        _homeView.taskClickBlock = ^{
            GPTaskView *taskView = [GPTaskView initGPTaskView];
            taskView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
            [weakSelf.view.window addSubview:taskView];
        };
        
        _homeView.redClickBlock = ^{
            [weakSelf taskMinuteDiamondsRequest];
        };
        
        _homeView.diamondClickBlock = ^{
            if (self.levelStatus.intValue == 0) {
                [SVProgressHUD showImage:NULL_IMAGE status:@"你的金猪还没达到等级，不能领取奖励"];
            }else if (self.levelStatus.intValue == 1){
                [weakSelf taskBonusesGetResquest:weakSelf.levelBonusesTypeId.intValue];
            }
        };
        
        _homeView.withdrawalCilckBlock = ^{
            weakSelf.levelUpView = [GPLevelUpView initGPLevelUpView];
            weakSelf.levelUpView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
            weakSelf.levelUpView.upCilckBlock = ^{
                [weakSelf buyLevelResquest];
                [weakSelf.levelUpView removeFromSuperview];
            };
            [weakSelf.view.window addSubview:weakSelf.levelUpView];
        };
        _homeView.mapCilckBlock = ^{
            GPMapController *vc = [[GPMapController alloc]init];
            vc.level = weakSelf.level;
            [weakSelf.navigationController pushViewController:vc animated:NO];
            
        };
        _homeView.getPigGoldCilckBlock = ^{
            [weakSelf getPigGoldResquest];
        };
        _homeView.checkCilckBlock = ^{
            [weakSelf.upgradeView setHidden:NO];
        };
        _homeView.workCilckBlock = ^{
            GPWorkController *vc = [[GPWorkController alloc]init];
            [weakSelf.navigationController pushViewController:vc animated:NO];
        };

    }
    return _homeView;
}

-(GPUpgradeView *)upgradeView{
    if (!_upgradeView) {
        _upgradeView = [GPUpgradeView initGPUpgradeView];
        _upgradeView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
        [_upgradeView setHidden:YES];
        [self.view addSubview:_upgradeView];
    }
    return _upgradeView;
}


#pragma mark 网络请求

-(void)taskBonusesSearchResquest{
    
    NSDictionary *dic = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:1] forKey:@"type"];
    [[GPRequsetManager HttpRequstManager] PostURL2:Tree_IP(taskBonusesSearch) params:dic  success:^(NSInteger code, id  _Nonnull result) {

        if (code == 1) {
          NSArray *data = result[@"data"];
            for (NSDictionary *d in data) {
                self.levelStatus = d[@"status"];
                if (self.levelStatus.intValue == 0) {
                    NSNumber *level = d[@"level"];
                    self.homeView.levelRewardLab.text = [NSString stringWithFormat:@"%@级",level];
                    self.homeView.levelRemainLayout.constant = 15;
                    [self.homeView.levelRewardLab setHidden:NO];
                    break;
                }else if (self.levelStatus.intValue == 1){
                    self.levelBonusesTypeId = d[@"bonusesTypeId"];
                    self.homeView.levelRemainLayout.constant = 0;
                    [self.homeView.levelRewardLab setHidden:YES];
                    break;
                }
                
            }
        }else{
            NSString *msg = result[@"msg"];
            [SVProgressHUD showImage:NULL_IMAGE status:msg];
        }

    } fail:^(NSError * _Nonnull error) {

    }];
}


-(void)taskBonusesGetResquest:(int)bonusesTypeId{
    NSDictionary *dic = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:bonusesTypeId] forKey:@"bonusesTypeId"];
    [[GPRequsetManager HttpRequstManager] PostURL2:Tree_IP(taskBonusesGet) params:dic success:^(NSInteger code, id  _Nonnull result) {
        if (code == 1) {
            
            NSDictionary *data = result[@"data"][0];
            NSNumber *amount = data[@"amount"];
  
            self.diamondsNum = [NSNumber numberWithInt:self.diamondsNum.intValue + amount.intValue];
            
            GPTipView *tipView = [GPTipView initGPTipView];
            tipView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
            [self.view.window addSubview:tipView];
            tipView.amount = amount;
            tipView.name = @"钻石";

            [self taskBonusesSearchResquest];
            
        }else{
            NSString *msg = result[@"msg"];
            [SVProgressHUD showImage:NULL_IMAGE status:msg];
        }
        
        
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

-(void)getPigInfoResquest{
    
    NSDictionary *dic = [[NSDictionary alloc]init];
    [[GPRequsetManager HttpRequstManager] PostURL2:Tree_IP(getPigInfo) params:dic  success:^(NSInteger code, id  _Nonnull result) {

        if (code == 1) {
            //NSLog(@"%@",result);
            [self.givenNumTimer invalidate];
            self.givenNumTimer = nil;
            
            NSArray *data = result[@"data"];
            NSDictionary *dic = data[0];

            self.capacity = dic[@"capacity"];
            self.givenNum = dic[@"givenNum"];
            self.level = dic[@"level"];
            NSNumber *currentNum = dic[@"currentNum"];
            NSNumber *levelUpNum = dic[@"levelUpNum"];
            
            self.homeView.levelProgress_layout.constant = currentNum.floatValue/levelUpNum.floatValue*70;
            self.upgradeView.levelProgress_layout.constant = (1-currentNum.floatValue/levelUpNum.floatValue)*169.0;
            self.upgradeView.nextLevelNumLab.text = [NSString stringWithFormat:@"再收取%d枚金币可升至下一级",levelUpNum.intValue - currentNum.intValue];
            self.upgradeView.levelLab.text = [NSString stringWithFormat:@"%@级",self.level];
            self.homeView.capacityLab.text = [NSString stringWithFormat:@"可存%@",self.capacity];
            self.homeView.level = self.level;
            
            self.givenNumTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(givenNumTimerHeadle) userInfo:nil repeats:YES];
        }

    } fail:^(NSError * _Nonnull error) {

    }];
}

- (void)setGivenNum:(NSNumber *)givenNum{
    _givenNum = givenNum;
    self.homeView.givenNumLab.text = [NSString stringWithFormat:@"%@",givenNum];
}


-(void)buyLevelResquest{
    
    NSDictionary *dic = [[NSDictionary alloc]init];
    [[GPRequsetManager HttpRequstManager] PostURL2:Tree_IP(buyLevel) params:dic  success:^(NSInteger code, id  _Nonnull result) {

        if (code == 1) {
            NSArray *data = result[@"data"];
            NSDictionary *dic = data[0];
            NSNumber *bonusesId = dic[@"bonusesId"];
            self.diamondsNum = [NSNumber numberWithInt:self.diamondsNum.intValue - 20000];
            if (bonusesId) {
               [self taskConsumeRequest:bonusesId];
            }
        }else{
            NSString *msg = result[@"msg"];
            [SVProgressHUD showImage:NULL_IMAGE status:msg];
        }

    } fail:^(NSError * _Nonnull error) {

    }];
}

-(void)redEnvelopedRainSearchResquest{
    
    NSDictionary *dic = [[NSDictionary alloc]init];
    [[GPRequsetManager HttpRequstManager] PostURL2:Tree_IP(redEnvelopedRainSearch) params:dic  success:^(NSInteger code, id  _Nonnull result) {

        if (code == 1) {
            [self.reTimer invalidate];
            self.reTimer = nil;
            
            NSArray *data = result[@"data"];
            NSDictionary *dic = data[0];
            self.remainTime = dic[@"remainTime"];
            self.remainNum = dic[@"remainNum"];
            if (self.remainNum.intValue > 0) {
                if (self.remainTime.intValue == 0) {
                    self.homeView.remainNumLab.text = [NSString stringWithFormat:@"免费%@次",self.remainNum];
                }else{
                    self.reTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(reTimerHeadle) userInfo:nil repeats:YES];
                }
            }else{
                self.homeView.remainNumLab.text = @"";
            }
            
        }else{
            NSString *msg = result[@"msg"];
            [SVProgressHUD showImage:NULL_IMAGE status:msg];
        }

    } fail:^(NSError * _Nonnull error) {

    }];
}



-(void)getPigGoldResquest{
    NSDictionary *dic = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:1937] forKey:@"bonusesTypeId"];
    [[GPRequsetManager HttpRequstManager] PostURL2:Tree_IP(getPigGold) params:dic success:^(NSInteger code, id  _Nonnull result) {
        if (code == 1) {
            
            NSDictionary *data = result[@"data"][0];
            NSNumber *givenNum = data[@"givenNum"];
            self.goldNum = [NSNumber numberWithInt:self.goldNum.intValue + givenNum.intValue];

            NSNumber *bonusesId = data[@"bonusesId"];
            if (bonusesId) {
                [self taskConsumeRequest:bonusesId];
            }else{
                GPTipView *tipView = [GPTipView initGPTipView];
                tipView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
                [self.view.window addSubview:tipView];
                tipView.amount = givenNum;
                tipView.name = @"金币";
                
                [self getPigInfoResquest];
            }
            
            
            
        }else{
            NSString *msg = result[@"msg"];
            [SVProgressHUD showImage:NULL_IMAGE status:msg];
        }
        
        
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

-(void)taskConsumeRequest:(NSNumber *)num{
    NSDictionary *dic = [NSDictionary dictionaryWithObject:@[num] forKey:@"bonusesTypeIds"];
    [[GPRequsetManager HttpRequstManager] PostURL2:Tree_IP(taskConsume) params:dic success:^(NSInteger code, id  _Nonnull result) {
        //NSLog(@"%@",result);
        
        if (code == 1) {
            
            NSDictionary *data = result[@"data"][0];
            NSNumber *amount = data[@"amount"];
            self.diamondsNum = [NSNumber numberWithInt:self.diamondsNum.intValue + amount.intValue];
            GPTipView *tipView = [GPTipView initGPTipView];
            tipView.level = self.level;
            tipView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
            [self.view.window addSubview:tipView];
            tipView.amount = amount;
            tipView.name  = @"升级";
            
            [self getPigInfoResquest];
            [self taskBonusesSearchResquest];
        }else{
            NSString *msg = result[@"msg"];
            [SVProgressHUD showImage:NULL_IMAGE status:msg];
        }
        
        
    } fail:^(NSError * _Nonnull error) {
        
    }];
}


-(void)userAccountRequest{
    NSDictionary *dic = [[NSDictionary alloc]init];
    [[GPRequsetManager HttpRequstManager] PostURL2:Tree_IP(userAccount) params:dic  success:^(NSInteger code, id  _Nonnull result) {

        if (code == 1) {
            //NSLog(@"%@",result);
            NSArray *data = result[@"data"];
            NSDictionary *dic = data[0];
            NSNumber *validGold = dic[@"validGold"];
            self.goldNum = validGold;

            NSNumber *validMoney = dic[@"validMoney"];
            self.diamondsNum = validMoney;
        }

    } fail:^(NSError * _Nonnull error) {

    }];
}

//分钟任务（钻石）
-(void)taskMinuteDiamondsRequest{
    NSDictionary *dic = [NSDictionary dictionaryWithObject:@[[NSNumber numberWithInt:1933]] forKey:@"bonusesTypeIds"];
    [[GPRequsetManager HttpRequstManager] PostURL2:Tree_IP(taskMinute) params:dic success:^(NSInteger code, id  _Nonnull result) {
        //NSLog(@"%@",result);
        
        if (code == 1) {
            
            NSArray *data = result[@"data"];
            NSDictionary *moneyDic = data[0];
            
            GPTipView *tipView = [GPTipView initGPTipView];
            tipView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
            [self.view.window addSubview:tipView];
            tipView.amount = moneyDic[@"amount"];
            tipView.name  = @"钻石";

            [self queryOfAppRequest];
            
        }else{
            NSString *msg = result[@"msg"];
            [SVProgressHUD showImage:NULL_IMAGE status:msg];
        }
        
        
    } fail:^(NSError * _Nonnull error) {
        
    }];
}


//查询特殊配置
-(void)queryOfAppRequest{
    NSDictionary *dic = [NSDictionary dictionaryWithObject:@[[NSNumber numberWithInt:1933]] forKey:@"bonusesTypeIds"];
    [[GPRequsetManager HttpRequstManager] PostURL2:Tree_IP(queryOfApp) params:dic success:^(NSInteger code, id  _Nonnull result) {
        NSLog(@"%@",result);
        
        if (code == 1) {
            [self.diamondsTimer invalidate];
            self.diamondsTimer = nil;

            NSDictionary *data = result[@"data"][0];
            self.bt_time_1933 = data[@"bt_time_1933"];
            self.diamondsTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(diamondsTimerHeadle) userInfo:nil repeats:YES];
            
        }
        
        
    } fail:^(NSError * _Nonnull error) {
        
    }];
}





#pragma mark 计时器
-(void)reTimerHeadle{
    if (self.remainTime.integerValue<=0) {
        [self.reTimer invalidate];
        self.reTimer = nil;
        self.homeView.remainNumLab.text = [NSString stringWithFormat:@"免费%@次",self.remainNum];
    }else{
        self.remainTime = [NSNumber numberWithInt:self.remainTime.intValue - 1];
    }
}


-(void)givenNumTimerHeadle{
    if (self.givenNum.integerValue>=self.capacity.intValue) {
        [self.givenNumTimer invalidate];
        self.givenNumTimer = nil;
        
        self.homeView.givenNumLab.text = [NSString stringWithFormat:@"%@",self.capacity];
    }else{
        self.givenNum = [NSNumber numberWithInt:self.givenNum.intValue + 1];
    }
}

-(void)diamondsTimerHeadle{
    if (self.bt_time_1933.integerValue<=0) {
        [self.diamondsTimer invalidate];
        self.diamondsTimer = nil;
        
        self.homeView.diamondsTimeLab.text = @"可领取";
    }else{
        self.bt_time_1933 = [NSNumber numberWithInt:self.bt_time_1933.intValue - 1];
    }
}


- (NSString *)hoursFormatted:(NSInteger)totalSeconds {
    NSInteger seconds = totalSeconds % 60;
    NSInteger minutes = (totalSeconds / 60) % 60;
    NSInteger hours = totalSeconds / 3600;
    if (hours) {
        return [NSString stringWithFormat:@"%02ld:%02ld:%02ld",hours, minutes, seconds];
    }
    return [NSString stringWithFormat:@"%02ld:%02ld",  minutes, seconds];
}
#pragma mark set
- (void)setBt_time_1933:(NSNumber *)bt_time_1933{
    _bt_time_1933 = bt_time_1933;
    self.homeView.diamondsTimeLab.text = [self hoursFormatted:bt_time_1933.integerValue];
}

- (void)setGoldNum:(NSNumber *)goldNum{
    _goldNum = goldNum;
    self.homeView.goldLab.text = [NSString stringWithFormat:@"%@",goldNum];
}

- (void)setDiamondsNum:(NSNumber *)diamondsNum{
    _diamondsNum = diamondsNum;
    self.homeView.diamondLab.text = [NSString stringWithFormat:@"%@",diamondsNum];
}
- (void)setRemainTime:(NSNumber *)remainTime{
    _remainTime = remainTime;
    self.homeView.remainNumLab.text = [self hoursFormatted:remainTime.integerValue];
}

@end
